package com.nisum.mocksimulator.externalize;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.nisum.mocksimulator.webservice.beans.CarType;

@Component
public class ExternalizableMessageWriter {
	@Value("#{null}")
	private String directory;
	
	public ExternalizableMessageWriter(){	
	}
	
	public boolean write(Object obj) {
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		CarType car = (CarType) obj;
		try {
			fos = new FileOutputStream(getFileName(this.directory));
			out = new ObjectOutputStream(fos);
			out.writeObject(car);
			out.flush();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			return false;
		}finally{
			if(fos != null && out != null){
				try {
					out.close();
					fos.close();
				} catch (IOException e) {
					System.out.println(e.getMessage());
					return false;
				}
			}
		}
		return true;
	}
	
	private String getFileName(String pathFolder) {
		String name = Math.random() + ".ser";
		String fileName = pathFolder + name;		
		return fileName;
	}

	public String getDirectory() {
		return directory;
	}

	public void setDirectory(String directory) {
		this.directory = directory;
	}
	
	
}
